package NG::Sys::Loop::EVDaemon;
use strict;
use warnings;
use utf8;

use EV;
use base 'NG::Sys::Loop::Daemon';

sub on_before_loop {
	my ($app) = @_;
	unless($app->SUPER::on_before_loop){
		return 0;
	}
	my $loop = EV::default_loop;
	$loop->loop_fork;

	my @sg;
	for my $s(qw(INT TERM HUP)){
		my $new;
		if(my $old = $SIG{$s}){
			$new = sub {
				EV::break EV::BREAK_ALL;
				&$old();
			};
			$SIG{$s} = undef;
		}else{
			$new = sub {
				EV::break EV::BREAK_ALL;
			};
		}
		push @sg,EV::signal( $s, $new );
	}
	$app->{my_signals} = \@sg;
	return 1;
}
sub on_delay_loop {
}
sub on_leave_loop {
	 return 1;
}
sub count_loop {
	my ($self) = @_;
	($self->{count_loop} ||= 0 )++;
	if($self->{restart_after} && $self->{restart_after} <= $self->{count_loop}){
		NG::Sys::Loop::Daemon::restart();
		EV::break EV::BREAK_ALL;
		return;
	}
	if($self->arg->{count} && $self->arg->{count} <= $self->{count_loop}){
		NG::Sys::Loop::Daemon::stop();
		EV::break EV::BREAK_ALL;
		return;
	}
}

sub on_after_loop {
	my ($app) = @_;
	delete $app->{my_signals};
	$app->SUPER::on_after_loop;
}
sub on_process {
	my($app) = @_;
	EV::loop;
	return 0;
}

1;
